<!-- 
语音通话（一对一可拖转）
废弃原因：
	由于需求改动要做群语音聊天；此文件作废
 -->
<template>
	<div>
		<audio ref="audioplay" :src="apifun.hrefURL+'/static/14060.mp3'"></audio>
		<div class="topcontrol curpoin">
			<div class="topcontrolr flex">
				<!-- <p class="topcontrolreach curpoin" @click="mini">
					<span class="curpoin el-icon-minus"></span>
				</p> -->
				<p class="topcontrolreach curpoin" @click="colsed">
					<span class="curpoin el-icon-close"></span>
				</p>
			</div>
		</div>
		<div class="voicemain">
			<div class="voicemain-head">
				<div class="voicemain-headavater">
					<img v-if="youMsg.avatar" :src="apifun.URLimg + youMsg.avatar" alt="头像" />
					<img v-if="!youMsg.avatar" src="@/assets/logosvg.png" alt="头像" />
				</div>
				<div class="voicemain-headname">{{ youMsg.realname }}</div>
				<div class="voicemain-headname" v-if="state == 1">正在等待对方接听</div>
				<div class="voicemain-headname" v-if="state == 2">邀请你语音通话</div>
				<div class="voicemain-headname" v-if="state == 3">通话中...</div>
				<div class="voicemain-headname" v-if="state == 4">通话结束</div>
			</div>
			<div class="voicemain-bottonbtn">
				<div class="voicemain-btnequipment" v-if="!iszcTRTC">当前设备浏览器不支持音频功能，请检查设备或转至手机继续语音</div>
				<div class="voicemain-btnequipment" v-if="microphonenum <= 0">未检测到麦克风，请检查设备或转至手机继续语音</div>
				<div class="voicemain-bottonbtnmain marginAuto flex" v-if="btnshow">
					<div class="voicemain-bottonbtneach flex">
						<img style="width:50px;height:50px" @click="exitRoomfun" src="@/assets/chat/stopvoice.png"
							alt="挂断" />
					</div>
					<div class="voicemain-bottonbtneach flex" v-if="state == 2">
						<img style="width:50px;height:50px" @click="sendcalljtfun" src="@/assets/chat/startvoice.png"
							alt="接听" />
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import { ipcRenderer } from "electron";
	import TRTC from 'trtc-sdk-v5';
	import utils from '@/utils/utils';
	export default {
		data() {
			return {
				infodataacitem: {},  // 拨打时对方数据
				statustype:1,  // 1拨打2接听
				answer: {}  ,// 推送数据
				
				state: 1, // 1正在等待对方接听 2邀请你语音 3通话中4结束
				sdkAppId: 1600046845,
				secretKey: '3c521e02d23c3b687a11bf15daa627dd3f642e89e7d07a9b4cdfd86450cae9f0',
				userInfo: {},
				userId: '',
				youID: '',
				youMsg: {},
				roomId: '',
				userSig: '',
				id: '', //  消息id
				order_id:'',
				
				iszcTRTC: false, // 检测是否支持TRTC
				microphonenum: 0,
				microphoneId: String,
				client: null,
				btnshow:false
			};
		},
		mounted() {
			this.userInfo = JSON.parse(localStorage.getItem('userInfo'));
			this.userId = this.userInfo.user_id.toString();
			this.isSupported(); // 检测浏览器是否支持TRTC
			this.getMicrophoneList(); //  获取麦克风设备列表
			this.$refs.audioplay.play();
			ipcRenderer.on("appendMessagedata", (event, newValue) => {
				let answer = newValue.data;
				this.answer = answer;
				this.order_id = answer.order_id;
				this.answerfun(answer);
			});
			ipcRenderer.on("statustypedata", (event, newValue) => {
			    this.statustype = newValue;
			});
			ipcRenderer.on("infodataacitemdata", (event, newValue) => {  // 拨打带过来
			    this.infodataacitem = newValue;
				this.order_id = newValue.order_id;
			});
			setTimeout(()=>{   // 等待接收数据
				console.log('voice-infodataacitem--',this.infodataacitem);
				console.log('voice-statustype--',this.statustype);
				console.log('voice-answer--',this.answer);
				if (this.statustype == 1) { // 拨打
					this.youMsg = {
						avatar: this.infodataacitem.avatar,
						mobile: this.infodataacitem.account,
						realname: this.infodataacitem.realname,
						user_id: this.infodataacitem.user_id,
					};
					
					this.youID = this.infodataacitem.user_id;
					this.id = utils.getUuid();
					this.callfun();
				} else { // 接听
					this.youMsg = {
						avatar: this.answer.fromUser.avatar,
						mobile: this.answer.fromUser.mobile,
						realname: this.answer.fromUser.realname,
						user_id: this.answer.fromUser.user_id,
					};
					this.youID = this.answer.fromUser.user_id;
					this.id = this.answer.id;
					this.state = 2;
				}
				this.btnshow = true;
				// 生成房间号
				let arr = [this.userId, this.youID];
				arr.sort((a, b) => a - b);
				this.roomId = arr[0] + '-' + arr[1];
				this.initClient();  // 初始化房间-进入房间、监听事件
			},1000)
		},
		methods: {
			answerfun(data){
				let extendsdata = data.extends;
				if (extendsdata.event == 'calling') { //  呼叫中
					this.state = 2;
				};
				if (extendsdata.event == 'acceptRtc') { // 通话
					this.state = 3;
					this.startLocalAudio();
					if (!this.$refs.audioplay.paused) {
						this.$refs.audioplay.pause();
					}
				};
				if (extendsdata.event == 'busy') { // 忙线
					this.$message({
						message: '忙线中；请稍后在拨',
						type: 'warning'
					});
					this.state = 4;
					this.client.exitRoom();
					this.client.stopLocalAudio();
					this.electron.ipcRenderer.send("childClose");
					this.roomId = '';
				};
				if (extendsdata.event == 'hangup') { // 挂断
					this.state = 4;
					this.roomId = '';
					this.client.stopLocalAudio();
					this.electron.ipcRenderer.send("childClose");
					if (!!this.$refs.audioplay) {
						this.$refs.audioplay.pause();
					}
				};
			},
			initClient() { // 初始化
				this.apifun.$post('/pc/im/getUserSign', {}).then((res) => {
					if (res.code == 200) {
						let datas = res.data;
						this.userSig = datas;
						let tetcdata = {
							mode: 'rtc',
							sdkAppId: this.sdkAppId,
							userId: this.userId,
							userSig: datas,
						};
						this.client = TRTC.create(tetcdata);
						this.enterRoomfun();
						this.handleClientEvents();
					}
				})
			},
			enterRoomfun() { // 进房
				let enterRoom = {
					strRoomId: this.roomId,
					sdkAppId: this.sdkAppId,
					userId: this.userId,
					userSig: this.userSig,
					autoReceiveAudio: true
				}
				this.client.enterRoom(enterRoom);
			},
			exitRoomfun() { // 退出房间
				let code = this.state == 3 ? 906 : this.state == 2 ? 903 : 902;
				this.state = 4;
				let sendData = {
					toContactId: this.youID,
					event: 'hangup',
					id: this.id,
					status: this.statustype,
					code: code,
					order_id:this.order_id
				};
				this.client.exitRoom();
				this.apifun.$post('/pc/im/sendToMsg', sendData).then((res) => {
					// console.log('挂断',res.data)
					if (res.code == 200) {
						let datas = res.data;
						// 将datas数据返回到聊天页面
						this.roomId = '';
						this.electron.ipcRenderer.send("chatsend",datas)
					};
					this.electron.ipcRenderer.send("childClose");
					this.client.stopLocalAudio();
					if (this.$refs.audioplay) {
						this.$refs.audioplay.pause();
					}
				});
			},
			callfun() { // 拨打
				let sendData = {
					toContactId: this.youID,
					id: this.id,
					status: 1, //  1拨打方 2接听方
					code: 901,
					event: 'calling',
					order_id:this.order_id
				}
				this.state = 1;
				this.apifun.$post('/pc/im/sendToMsg', sendData).then((res) => {
					// console.log(res)
					if (res.code == 200) {
						let datas = res.data;
						if(datas.extends.code == 907){  // 忙线
							this.electron.ipcRenderer.send("childClose");
							this.client.exitRoom();
						}
					}
				})
			},
			sendcalljtfun() { // 接听
				let sendData = {
					toContactId: this.youID,
					id: this.id,
					status: 2, //  1拨打方 2接听方
					code: 901,
					msg_id: this.answer.msg_id,
					event: 'acceptRtc',
					order_id:this.order_id
				}
				this.state = 3;
				this.startLocalAudio()
				this.apifun.$post('/pc/im/sendToMsg', sendData).then((res) => {
					// console.log(res)
					if (res.code == 200) {
						if (!this.$refs.audioplay.paused) {
							this.$refs.audioplay.pause();
						}
					}
				})
			},
			async startLocalAudio() {
				this.client.enableAudioVolumeEvaluation(500);
				// setSystemAudioLoopbackVolume
				this.client.setRemoteAudioVolume('*',100);
				this.client.startLocalAudio();
				// this.client.updateLocalAudio({ mute: false });
			},
			handleClientEvents() { // 监听事件
				let that = this;
				// client.on('peer-leave')   远端退房
				this.client.on('error', (error) => {
					console.error('on-error--', error);
				});
				this.client.on('connection-state-changed', (
				event) => { //  'DISCONNECTED'：连接断开		'CONNECTING'：正在连接中		'CONNECTED'：已连接
					const prevState = event.prevState;
					const curState = event.state;
					if (prevState == 'CONNECTING' && curState == "DISCONNECTED") { // 失败
						this.exitRoomfun()
					}
					if (prevState == 'CONNECTED' && curState == "DISCONNECTED") { // 失败
						this.exitRoomfun()
					}
				});
				this.client.on('remote-user-exit', (event) => { // 退出房间
					this.client.exitRoom();
					this.client.stopLocalAudio();
					this.roomId = '';
					this.electron.ipcRenderer.send("childClose");
				});
			
				this.client.on('remote-audio-available', (event) => { // 收到远端进入房间
					console.error('远端用户发布音频--', event);
					// that.state = 3;
					// this.startLocalAudio();
					// this.$refs.audioplay.pause();
				});
				this.client.on('remote-audio-unavailable', (event) => { // 远端退出房间
					console.error('远端用户关闭音频--', event);
					that.state = 4;
					this.exitRoomfun();
					this.electron.ipcRenderer.send("childClose");
				});
			},
			colsed() {  // 关闭
				this.exitRoomfun();
				setTimeout(()=>{
					this.electron.ipcRenderer.send("childClose");
				},5000)
			},
			mini() {  // 缩小
				this.electron.ipcRenderer.send("child-mini");
			},
			async getMicrophoneList() { // 检测麦克风设备列表
				const microphoneList = await TRTC.getMicrophoneList();
				if (microphoneList[0] && microphoneList[0].getCapabilities) {
					const {
						channelCount
					} = microphoneList[0].getCapabilities();
					this.microphonenum = channelCount.max
				}
			},
			async isSupported() { // 检测浏览器是否支持TRTC
				TRTC.isSupported().then((checkResult) => {
					if (!checkResult.result) {
						console.log('checkResult', checkResult.result, 'checkDetail', checkResult.detail);
						// SDK 不支持当前浏览器，引导用户使用最新版的 Chrome 浏览器。
						this.iszcTRTC = false
					} else {
						this.iszcTRTC = true
					}
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	.topcontrol {
		position: fixed;
		top: 0;
		z-index:99;
		-webkit-app-region: drag;
		width: 100%;
		height: 30px;
		background-color: #fff;
		padding-bottom:10px;
		border-bottom: 1px solid #cccccc;
		.topcontrolr {
			-webkit-app-region: no-drag;
			// width: 100px;
			width: 50px;
			height: 30px;
			padding-top: 10px;
			position: absolute;
			right: 10px;
			top: 0px;
			justify-content: flex-end;

			.topcontrolreach {
				width: 30px;
				height: 30px;
				line-height: 30px;
				margin-left: 10px;
				line-height: 30px;
				font-size: 20px;
				text-align: center;
				border-radius:10px;
			}
			.topcontrolreach :hover{
				background-color: var(--mainColor);
				color: #fff;
			}
		}
	}
	// 内容
	.voicemain {
		position: relative;
		top:50px;
		width: 340px;
		height: 550px;
		background-color: #fff;
	}
	
	.voicemain-head {
		width: 100%;
	
		.voicemain-headavater {
			width: 100px;
			height: 100px;
			margin: auto;
			img {
				width: 100px;
				height: 100px;
			}
		}
	
		.voicemain-headname {
			line-height: 40px;
			font-size: 14px;
			text-align: center;
			color: #333;
		}
	}
	
	.voicemain-bottonbtn {
		position: absolute;
		width: 100%;
		bottom: 40px;
		z-index: 0;
	
		.voicemain-btnequipment {
			width: 70%;
			text-align: center;
			padding: 10px;
			background-color: #F4F4F4;
			border-radius: 8px;
			color: #333;
			font-size: 14px;
			line-height: 20px;
			margin: 0 auto 20px;
		}
	
		.voicemain-bottonbtnmain {
			width: 90%;
			justify-content: space-around;
	
			.voicemain-bottonbtneach {
				width: 50px;
				height: 50px;
				border-radius: 50%;
			}
		}
	
	}
</style>